package gunglad.com.utils

import java.sql.{Connection, PreparedStatement}
import java.util.Properties

import com.alibaba.druid.pool.DruidDataSourceFactory
import javax.sql.DataSource
//import org.apache.hadoop.hdfs.web.JsonUtil

/**
 * @author chenjie
 * @date 2020/11/29 20:03
 */
object JDBCUtil {

  val dataSource = init()

  def setProperty(properties: Properties, key: String,
                  map: Map[String, String], default: String): Unit = {
    //    properties.setProperty("username",username)
    //    var username= default
    if (map.contains(key)) {
      val value = map(key)
      properties.setProperty(key, value)
      return
    }
    properties.setProperty(key, default)

  }

  //  scala 读文件
  def init(): DataSource = {
    //  def init(): Unit = {
    val properties = new Properties()
//    val path = "D:\\proj\\hadoop\\spark_demo_code\\spark\\db.json"
//        val path = "/home/app/software/db.json"
        val path = "/home/app/private-conf/db.json"
//    /home/app/private-conf
///home/app/private-conf
    val map = JsonUtil.jsonFileToMap(path)
    //    Error:(23, 13) not found: value JsonUtil
    //    val map= JsonUtil.  jsonFileToMap(path)
    ////    JsonUtil.jsonFileToMap()
    //   val map=  jsonFileToMap(path)
    //   var username= map("username")
    var username = "root"
    if (map.contains("username")) {
      //      username=map("username"):String
      //      username=map("username").toString
      username = map("username")
    }
    var password = "123456"
    if (map.contains("password")) {
      password = map("password")
    }
    var url = "jdbc:mysql://localhost:3306/problemsolvingsystem?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai"
    if (map.contains("url")) {
      url = map("url")
    }

    //    if(username==null){
    //      username="root"
    //    }


    //    JsonUti
    //    JsonUtil.
    //    ScalaJsonParse
    properties.setProperty("driverClassName", "com.mysql.jdbc.Driver")
    //    properties.setProperty("username","root")
    //    properties.setProperty("password","123456")

    properties.setProperty("username", username)
    properties.setProperty("password", password)
    properties.setProperty("url", url)
    println("properties")
    println(properties)
    //    DruidDataSourceFactory.createDataSource( 没有返回
    //    try scala
    //    DruidDataSourceFactory.createDataSourc 没有返回
    try {
      return DruidDataSourceFactory.createDataSource(properties)
    } catch {
      case e: Exception => {
        println(e)
        return null
      }
    }
    //    println("Rest of the code is executing...")
    //更多请阅读：https://www.yiibai.com/scala/scala-try-catch.html


    //    try {
    //     return DruidDataSourceFactory.createDataSource(properties)
    //    }catch ( e:Exception){
    //      println(e)
    //    }

  }

  def getConnection: Connection = {
    dataSource.getConnection()
  }

  def main(args: Array[String]): Unit = {
    val connection = getConnection
    println("connection")
    println(connection)
    //    println("dataSource")
    //    println(dataSource)

    val sql = "insert into all_visit_count(college_name,date,man_visit) values(?,?,?) " +
      "on duplicate key update man_visit = man_visit + ?"
    val sum = 1
    println("sum")
    println(sum)
    println("sql")
    println(sql)
    val pstmt = JDBCUtil.executeUpdate(connection, sql, Array("info._2", "2022-1-1", sum, sum))
    println("pstmt")
    println(pstmt)
  }

  def executeUpdate(connection: Connection, sql: String, params: Array[Any]) = {
    var rtn = 0
    var pstmt: PreparedStatement = null
    try {
      connection.setAutoCommit(false)
      pstmt = connection.prepareStatement(sql)

      if (params != null && params.length > 0) {
        for (i <- params.indices) {
          pstmt.setObject(i + 1, params(i))
        }
      }
      rtn = pstmt.executeUpdate()
      connection.commit()
      pstmt.close()
    } catch {
      case e: Exception => e.printStackTrace()
    }
    rtn
  }

  def isExist(connection: Connection, sql: String, params: Array[Any]) = {
    var flag = false;
    var pstmt: PreparedStatement = null
    try {
      pstmt = connection.prepareStatement(sql)
      for (i <- params.indices) {
        pstmt.setObject(i + 1, params(i))
      }
      flag = pstmt.executeQuery().next()
      pstmt.close()
    } catch {
      case e: Exception => e.printStackTrace()
    }
    flag
  }

}
